export class AuthManager{
    static setToken(token)
    {
        console.log("into");
        localStorage.setItem('blog_token',token);
        console.log("level");
    }
    static getToken()
    {
        return localStorage.getItem('blog_token');
    }
    static clearToken()
    {
        localStorage.removeItem('blog_token');
    }
    static isLoggedIn()
    {
        return !!this.getToken();
    }
}
export class BlogApi{

    static async request(endpoint,options={}){
        const token=AuthManager.getToken();
        const headers={
            'Content-Type':'application/json',
            ...(options.headers || {}) // 确保合并前是对象
        };
        if(token){
            headers['Authorization']=`Bearer ${token}`;
            console.log(token);
        }

        try {
    
            const config = { 
            method: options.method || 'GET',
            headers,   
            body: options.body ? JSON.stringify(options.body) : undefined
    
            }  
            const response = await fetch(endpoint, config);
        if (!response.ok) {
            const error = await response.json().catch(() => ({}));
            throw new Error(`HTTP ${response.status}: ${error.message || response.statusText}`);
          }   
        return response.json();
    }
     catch (error) {
        console.error('完整错误堆栈:', error);
        console.error('请求配置:', { endpoint, config });
        
        // 弹窗前记录详细信息
        const errorDetail = {
          message: error.message,
          stack: error.stack,
          timestamp: new Date().toISOString()
        };
        localStorage.setItem('lastError', JSON.stringify(errorDetail));
        
        throw error; // 保持原有抛出逻辑
      }
    }
    static async getBlogs(page=1){
        return this.request(`/blog/blog_cgi/mysql_blogs?page=${page}&limit=10`);
    }
    static async createBlog(title,content){
        return this.request('/blog/blog_cgi/mysql_create',{
            method:'POST',
            body:JSON.stringify({title,content})
        });

    }
    static async deleteBlog(blogId){
        return this.request(`/blog/blog_cgi/mysql_detel?${blogId}`);
    }
}

function renderBlogList(blogs)
{
const blogcontainer=document.getElementById('bloglist');

console.log(blogs.data.length);
    if(!blogs.data.length)
    {
        blogcontainer.innerHTML='<p>暂无博客内容<\p>';
        return;
    }
    // 使用模板字符串生成HTML
  const html = blogs.data.map(blog => `
  <div class="blog-card">
    <h2>${blog.title}</h2>
    <div class="meta">
      <span>作者：${blog.userid}</span>
      <span>日期：${new Date(blog.create).toLocaleDateString()}</span>
    </div>
    <p>${blog.content.slice(0, 100)}...</p>
    <a class="bloglink" deta-blogid="${blog.blogid}" href="#detail?blogid=${blog.blogid}" >阅读更多</a>
  </div>
`).join('');

// 5. 插入到容器
blogcontainer.innerHTML = html;
};
//博客主页加载
export async function loadBlogList(){
    try{
       const jsonBlogs=await BlogApi.getBlogs();
        console.log(jsonBlogs);
        return jsonBlogs;
    }catch(error)
    {
    console.log(error.message)
    
            //token过期 
           // window.location.href='/blog/blog_html/blog_login.html';
    }
}
export async function deleteBlog(blogId){
    if(confirm('你确定要删除这篇博客吗?')){
        await BlogApi.deleteBlog(blogId);
    }

}